package com.lance.answer.gui.answer.gk.video.tmp.tmp;

import com.google.common.base.Strings;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.video.dto.WatchVideoDto;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

@Slf4j
public class WatchVideo1010XijingpingTasktmpppp extends Thread {

    private final String driverPath;
    private final LinkedBlockingDeque<WatchVideoDto> watchVideos;

    public WatchVideo1010XijingpingTasktmpppp(String driverPath, LinkedBlockingDeque<WatchVideoDto>  watchVideos) {
        this.driverPath = driverPath;
        this.watchVideos = watchVideos;
    }

    @SneakyThrows
    @Override
    public void run() {

        while (watchVideos.size() > 0) {
            WatchVideoDto  watchVideo = watchVideos.take();
            String userName = watchVideo.getUserName();
            String password = watchVideo.getPassword();
            log.info("任务：{} 剩余 {} 行 用户名：{} 密码：{}",
                    Thread.currentThread().getName(), watchVideos.size(), userName, password);
            System.err.println("执行任务11111");
            run(driverPath,watchVideo);
        }

        if (watchVideos.size() == 0) {
            log.info("课程所有用户均已执行完毕，系统将在20min后结束");
            TimeUnit.MINUTES.sleep(20);
            return;
        }
    }


    public static void run(String driverPath,WatchVideoDto  watchVideo) throws Exception {

        String subjectName = watchVideo.getSubjectName();
        String userName = watchVideo.getUserName();
        String password = watchVideo.getPassword();
        String loginUrl = watchVideo.getLoginUrl();
        String JS = watchVideo.getJS();
        int completeVideoSize = watchVideo.getCompleteVideoSize();
        // 校验是否完成；
        if(Util.checkCompleteVideo("libsTmp//answerInfo//",subjectName,userName,completeVideoSize)){
            System.err.println("?????????????????????????????????1111111111111111111111111111");
            return;
        }

        ChromeDriver driver = Util.getDriver(driverPath);

        try {
            String url = "http://passport.ouchn.cn/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dstudentspace%26redirect_uri%3Dhttp%253A%252F%252Fstudent.ouchn.cn%252F%2523%252Fsignin-oidc%2523%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520ouchnuser%2520ouchnstudentspaceapi%2520offline_access%26state%3Dca1cb5d0270b49fdaea508b8a846c457%26nonce%3Dd257df51b0a141ac8ed35b1caf59ef4c";
            driver.get(url);
            Thread.sleep(6000);
            Util.login(driver, userName, password);
            //Util.switchToLast(driver);
            Thread.sleep(6000);
            // 形考作业的链接 管理学

            boolean isFind = false;
            for (WebElement we : driver.findElements(By.className("media-body"))) {
                String mediaTitle = we.findElement(By.className("media-title")).getText();

                if (!mediaTitle.contains(subjectName)) {
                    continue;
                }
                //点击进入学习的按钮
                WebElement studyButton = we.findElement(By.cssSelector("button[class='btn bg-primary']"));
                studyButton.click();
                isFind = true;
                //Util.switchToLast(driver);
                Thread.sleep(6000);
            }

            if (!isFind) {
                return;
            }

            // TODO 在这里统计有多少个视频已经刷了
            Util.switchToLast(driver);

            int index = 1;
            //sectionname

            int h3ListSize = driver.findElements(By.cssSelector("h3[class='sectionname']")).size();

            System.err.println("h3ListSize:"+h3ListSize);

            String courseUrl = driver.getCurrentUrl();
            // 点击后 还得把之前得收起来
            int tmpIndex = -1;
            for (int i = 0; i < h3ListSize; i++) {
                List<WebElement> h3List = driver.findElements(By.cssSelector("h3[class='sectionname']"));
                WebElement h3 = h3List.get(i);

                String h3Text = h3.getText();
                System.err.println("h3Text:"+h3Text);
                if (Strings.isNullOrEmpty(h3Text)) {
                    continue;
                }
                if (!h3Text.contains("专题")&&!h3Text.contains("总论")) {
                    continue;
                }
                // >0 是因为第一次 就是导论，不能刷新
                if(tmpIndex>=0){
                    WebElement wh3= driver.findElement(By.cssSelector("div[class='content act']")).findElement(By.className("sectionname"));
                    String h3Text222 = wh3.getText();
                    System.err.println("h3Text222:"+h3Text222);
                    if (Strings.isNullOrEmpty(h3Text222)) {
                        continue;
                    }
                    wh3.click();
//                        if (h3Text222.contains("总论")) {
//                            wh3.click();
//                        }

                }
                if (index > 1) {
                    System.err.println("indexxx:"+index);
                    ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,100000)");
                }

                tmpIndex = i;
                //     System.err.println("index:"+index);
                if (h3Text.contains("专题")) {

                    System.err.println("???????????????????");
                    index++;
                    h3.click();
                    Thread.sleep(2000);
                }
                if (h3Text.contains("总论")) {
                    System.err.println("总论..........");
                    index++;
                //    h3.click();
                    Thread.sleep(2000);
                }

                //  List<WebElement> activityinstanceList = driver.findElements(By.cssSelector("li[class^='activity url modtype_url']"));
                //     List<WebElement> activityinstanceList = driver.findElements(By.cssSelector("li[class^='activity url modtype_url'],li[class^='activity quiz modtype_quiz']"));

//                List<WebElement> activityinstanceList = driver.findElement(By.cssSelector("div[class='content act']"))
//                        .findElements(By.cssSelector("li[class^='activity url modtype_url'],li[class^='activity quiz modtype_quiz']"));
                List<WebElement> activityinstanceList = driver.findElement(By.cssSelector("div[class='content act']"))
                        .findElements(By.cssSelector("li[class^='activity url modtype_url'],li[class^='activity quiz modtype_quiz']"));
                if (activityinstanceList == null || activityinstanceList.size() == 0) {
                    return;
                }

                System.err.println("activityinstanceList.size():" + activityinstanceList.size());

                boolean watch = false;
                for (int j = 0; j < activityinstanceList.size(); j++) {
                    // 回到页面再次点击
                    if (j > 0 && watch) {

                        Thread.sleep(3000);
                        List<WebElement> h3List2 = driver.findElements(By.cssSelector("h3[class='sectionname']"));

                        // 每次刷新都是导论
                        for(WebElement wh3:h3List2){
                            String h3Text2 = wh3.getText();
                            System.err.println("h3Text2:"+h3Text2);
                            if (Strings.isNullOrEmpty(h3Text2)) {
                                continue;
                            }
                            if (h3Text2.contains("总论")) {
                                wh3.click();
                            }
                        }
                        Thread.sleep(2000);

                        WebElement h32 = h3List2.get(i);
                        System.err.println("??????????????????????j="+j+"  i="+i);
                        watch = false;
                        h32.click();
                        Thread.sleep(5000);
                    }
                      System.err.println("!!!!!!!!!!!!!!!!!!!!j="+j+"  i="+i);

//                    List<WebElement> realActivityinstanceList = driver.findElement(By.cssSelector("div[class='content act']"))
//                            .findElements(By.cssSelector("li[class^='activity url modtype_url'],li[class^='activity quiz modtype_quiz']"));
                    List<WebElement> realActivityinstanceList = driver.findElement(By.cssSelector("div[class='content act']"))
                            .findElements(By.cssSelector("li[class^='activity url modtype_url'],li[class^='activity quiz modtype_quiz']"));
                    WebElement activityinstance = realActivityinstanceList.get(j);
                    String instanceText = activityinstance.getText();
                    //   System.err.println("instanceText:"+instanceText);
                    if (Strings.isNullOrEmpty(instanceText)) {
                        continue;
                    }

                    try {

                        // FIXME 有两种判断方法
                        WebElement btnWe = Util.findByCssSelector(activityinstance, "button[class='btn btn-link'],span[class='autocompletion']");
                        if (btnWe == null) {
                            continue;
                        }
                        WebElement imgWe = Util.findByCssSelector(btnWe, "img[class^='icon']");
                        if (imgWe == null) {
                            watchVideo(driver, activityinstance,courseUrl,JS);
                            // =0就是刷新导论
                            tmpIndex = 0;
                            // 为空 也要点击 因为 11-7
                            continue;
                        }
                        String imgText = imgWe.getAttribute("title");
                        //    System.err.println("imgText:"+imgText);
                        if (Strings.isNullOrEmpty(imgText)) {
                            continue;
                        }
                        if (!imgText.contains("已完成")) {
                            watchVideo(driver, activityinstance,courseUrl,JS);
                            // =0就是刷新导论
                            tmpIndex = 0;
                            watch = true;
                          //  driver.navigate().refresh();
                            Thread.sleep(3000);
                        } else {
                            watch = false;
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                Thread.sleep(4000);
            }

            Thread.sleep(4000);

            //System.out.println(urlTasks.toString());
        } catch (Exception e) {
            e.printStackTrace();
            Thread.sleep(2000);
        } finally {
            try {
                driver.close();
                driver.quit();
            } catch (Exception e) {

            }
        }
    }

    // static void watchVideo(WebDriver driver,String urlTask)throws Exception{
    static void watchVideo(WebDriver driver, WebElement activityinstance,String courseUrl,String JS) throws Exception {

        System.err.println("开始观看视频！！！！！！！！！");
        //    Util.switchToFirst(driver);
        // FIXME 当完成第一份形考任务时，必须提交，否则会弹出 ”是否保存当前页面“消息
        //  activityinstance.click();
        activityinstance.findElement(By.tagName("a")).click();

        //延长加载时间
        Thread.sleep(5 * 1000);
        // Util.switchToUrl(driver,urlTask);
        Util.switchToLast(driver);
        Thread.sleep(2 * 1000);
        ((JavascriptExecutor) driver).executeScript(JS);
        Thread.sleep(2 * 1000);
        List<WebElement> canvas = driver.findElements(By.tagName("canvas"));
        //System.out.println("canvas大小");
        //System.out.println(canvas.size());
        for (WebElement player : canvas) {
            //System.out.println("class是：" + player.getAttribute("class"));
            if (player.getAttribute("class").startsWith("play")) {
                //System.out.println("找到啦 ");
                //System.out.println(player);
                player.click();
            } else {
                continue;
            }
        }

        Thread.sleep(18000);
     //FIXME    driver.navigate().back();
     //   driver.get("http://xinjiang.ouchn.cn/course/view.php?id=1967");
        driver.get(courseUrl);
    }


    private static List<WebElement> findWeElements(WebDriver driver, String cssSelector, int second) {
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                });
    }


}
